import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { StationDTO } from '@/services/api/stationApi';
import { RESET_ALL_STATE } from '../actions/resetActions';

export type FullSceneState = {
  stationList: StationDTO[];
  currentStation: StationDTO | null;
};

const initialState: FullSceneState = {
  stationList: [],
  currentStation: null,
};

const fullSceneSlice = createSlice({
  name: 'fullScene',
  initialState,
  reducers: {
    setStationList: (state, action: PayloadAction<StationDTO[]>) => {
      state.stationList = action.payload;
      if (!state.currentStation) {
        state.currentStation = action.payload[0];
      } else {
        const findStation = action.payload.find(
          (station) => station.id === state.currentStation?.id
        );
        if (!findStation) {
          state.currentStation = action.payload[0];
        } else {
          state.currentStation = findStation;
        }
      }
    },
    setCurrentStation: (state, action: PayloadAction<StationDTO>) => {
      // if (state.currentStation?.id !== action.payload.id) {
      state.currentStation = action.payload;
      // }
    },
    // 重置电站状态
    resetFullSceneState: (state) => {
      state.stationList = [];
      state.currentStation = null;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(RESET_ALL_STATE, (state) => {
      // 重置到初始状态
      Object.assign(state, initialState);
    });
  },
});

export const { setStationList, setCurrentStation, resetFullSceneState } = fullSceneSlice.actions;

export default fullSceneSlice.reducer;
